/**
 * 
 */
package phoenics.manpads.common.interceptor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import phoenics.manpads.common.exception.BaseResult;
import phoenics.manpads.common.exception.NoWarpperResult;
import phoenics.manpads.common.utils.JacksonUtil;

/**
 * @author Phoenics Chow 
 * on 2018年5月17日
 *
 */
//@RestControllerAdvice
public  class ResultResponse implements ResponseBodyAdvice<Object> {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ResultResponse.class);

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#supports(org.springframework.core.MethodParameter, java.lang.Class)
	 */
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		//return returnType.getMethod().getReturnType().getTypeName().equals("void");
		return true;
	}

	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice#beforeBodyWrite(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.http.MediaType, java.lang.Class, org.springframework.http.server.ServerHttpRequest, org.springframework.http.server.ServerHttpResponse)
	 */
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		response.getHeaders().add("content-type", "text/html;charset=utf-8");
		if(body instanceof BaseResult ) {
			return body;
		}
		if(body instanceof NoWarpperResult) {
			NoWarpperResult w=(NoWarpperResult)body;
			return w.getData();
		}
		BaseResult res=BaseResult.success(body);
		if(body instanceof String) {
			return  JacksonUtil.toJSon(res);
		}
		return res;
	}



	
}
